<template>
  <div>
    <el-row class="myFrom" type="flex" justify="center">
      <el-col :span="18">
        <h1>登录啊</h1>
        <el-form ref="form" :rules="rules" :model="form" label-width="80px">
          <el-form-item label="用户名" prop="name">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="用户密码" prop="password">
            <el-input v-model="form.password" show-password></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit('form')">登录</el-button>
            <el-button>取消</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  /* 到 qs 工具包 */
  import qs from "qs"
  export default {
    name: "Login",
    data() {
      return {
        form: {
          name: '',
          password: ''
        },
        rules: {
          name: [
            {required: true, message: '请输入用户名称', trigger: 'blur'},
            {min: 4, max: 8, message: '长度在 4 到 8 个字符', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '请输入用户密码', trigger: 'blur'},
            {min: 4, max: 8, message: '长度在 4 到 8 个字符', trigger: 'blur'}
          ]
        }
      }
    },
    methods: {
      onSubmit: function (formName) {
        //创建变量接受实例对象,方便在回调函数中使用
        var v = this;
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.axios({
              url: "http://10.36.141.177:8081/test/login",
              method:"post",
              transformRequest:[
                function (data) {
                    // alert(JSON.stringify(data));
                    return qs.stringify(data);
                }
              ],
              data:{
                name:this.form.name,
                password:this.form.password
              }
            }).then(function (response) {
                // console.log(response.data)
              // alert(this);
              if (response.data!=null){
                //保存数据到store 全局对象当中,相当于保存到session
                v.$store.dispatch('asyncUpdateUser', response.data);
                v.$message({
                  message: '恭喜你，这是一条登录成功消息',
                  type: 'success'
                });
                v.$router.push("/Index");
              }else{
                v.$message.error('哦呵呵呵呵,你猜发生什么事');
              }
            })
          } else {
            this.$message.error('傻子,^_^~');
            return false;
          }
        });
      }
    }
  }
</script>

<style scoped>
  .myFrom {
    border-radius: 10px;
    width: 500px;
    margin: 50px auto;
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
  }
</style>
